﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


using YT.DB;
using YT.Commons;
using YT.AdvanceCommons;

namespace YT.XH.MF
{
    public partial class frmMoutputMtn : Form
    {
        private DBAccess mdbcon = new DBAccess(false, false);
        public frmMoutputMtn()
        {
            InitializeComponent();
        }

        private bool BackUpData()
        {
            DBAccess dbcon = new DBAccess(false, false);
           

            string strSQL = "select * from muser";
            DataTable dt = dbcon.GetDataTable(strSQL);
            string strFieldName = Application.StartupPath + "\\xmluser";
            dt.WriteXml(strFieldName);


            DataSet ds = new DataSet();
            ds.ReadXml(strFieldName);
            foreach (DataRow drRow in ds.Tables[0].Rows)
            {
                string username = CvtFunc.ToString(drRow["Username"]);
            }
            return true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void FrmMoutputMtn_Load(object sender, EventArgs e)
        {
            this.Text = "数据上报";
            FillData();
        }

        private bool GenerateData(string strPath, DBAccess dbcon)
        {
            try
            {
                string strCondition = string.Empty;
                //string strFieldName = Application.StartupPath;
                string strFieldName = strPath;
                strFieldName += "\\" + "上报数据" + SysVar.HospitalID + BaseFunctions.FormatDate(DateTime.Now.Date.ToString() , DateFormatOption.DateFmtYMD).Replace("\\", "").Replace("/", "");

                if (Directory.Exists(strFieldName))
                    Directory.Delete(strFieldName, true);

                Directory.CreateDirectory(strFieldName);
                System.Threading.Thread.Sleep(1000);
                strCondition = " where 1=1 ";

                string strSQL = @" Select distinct tablename from mOutputTableName where tablename in (
                                   SELECT name
                                   FROM sysobjects
                                   WHERE (xtype = 'U') )";
                DataTable dtTableName = dbcon.GetDataTable(strSQL);
                foreach (DataRow drTableName in dtTableName.Rows)
                {
                    string strTableName = CvtFunc.ToString(drTableName["TableName"]);
                    strSQL = "select * from " + strTableName + " ";
                    DataTable dtTable = dbcon.GetDataTable(strSQL);
                    dtTable.WriteXml(strFieldName + "\\" + strTableName + ".xml");
                }
                string strEmail = @"vertigo115@yahoo.cn" ;
                if (SysVar.IsNose)
                {
                    strEmail = "jj-c@tom.com";
                }
                if (RunRar(strFieldName, strPath))
                {
                    MessageBox.Show("数据产生成功。\r\n文件名称: " + strFieldName + ".Rar", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageBox.Show("请将 上报文件发送至  " + strEmail);
                }
                else
                    return false;

               // System.Diagnostics.Process.Start("C:\\");
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
            return true;
        }

        private bool RunRar(string strFieldName,string strPath)
        {
            try
            {

                string strzipPath = string.Empty;
                string strtxtPath = string.Empty;
                strzipPath = "\"" + strPath + "\"" + "\\上报数据" +SysVar.HospitalID + BaseFunctions.FormatDate(DateTime.Now.Date.ToString() , DateFormatOption.DateFmtYMD).Replace("\\", "").Replace("/", "") +".rar";
                strtxtPath = "\""+ strFieldName +"\"" + "\\*.*";
                System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                Process1.StartInfo.FileName = Application.StartupPath +"\\WinRAR.exe";
                Process1.StartInfo.Arguments = " a -v2048 -r " + strzipPath + " " + strtxtPath + " -ep" + " -pUnionPassW0rd";
                Process1.Start();
                Process1.WaitForExit();
                if (Process1.HasExited)
                {
                    int iExitCode = Process1.ExitCode;
                    if (iExitCode == 0)
                    {
                        //正常完成
                    }
                    else
                    {
                        MessageBox.Show("产生文件时发生错误，请检查。", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                Process1.Close();
            }                
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
            return true;
        }

        private void FillData()
        {
            int intRow = 0;
            string strSQL = string.Empty;
            this.dgvDtl.Rows.Clear();
            strSQL = "select * from mOutputHistory order by recid";
            DataTable dtDtl = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drRow in dtDtl.Rows)
            {
                this.dgvDtl.Rows.Add();
                this.dgvDtl.Rows[intRow].Cells[ColSeqNo.Index].Value = CvtFunc.ToString(drRow["SeqNo"]);
                this.dgvDtl.Rows[intRow].Cells[ColUserName.Index].Value = CvtFunc.ToString(drRow["UserName"]);
                //this.dgvDtl.Rows[intRow].Cells[ColRemark.Index].Value = CvtFunc.ToString(drRow["Remark"]);
                //this.dgvDtl.Rows[intRow].Cells[ColFromDate.Index].Value = BaseFunctions.FormatDate (  CvtFunc.ToString(drRow["FromDate"]), DateFormatOption.DateFmtYMD )  ;
                //this.dgvDtl.Rows[intRow].Cells[ColToDate.Index].Value = BaseFunctions.FormatDate(CvtFunc.ToString(drRow["ToDate"]), DateFormatOption.DateFmtYMD);
                this.dgvDtl.Rows[intRow].Cells[ColDate.Index].Value = BaseFunctions.FormatDate(CvtFunc.ToString(drRow["OutputDate"]), DateFormatOption.DateFmtYMD);       
                intRow++;
            }
            
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要生成上报数据？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {                
                saveFileDialog1.ShowDialog();
                string strPath = saveFileDialog1.FileName ;
                if (strPath == "") return;
                if ( MessageBox.Show ( "请确保有足够的空间和权限进行本次操作. ", "", MessageBoxButtons.YesNo , MessageBoxIcon .Question )== DialogResult.Yes)
                {
                    mdbcon.BeginTran();
                    string strSeqNo = DataFunctions.GetFieldValue("mOutputHistory", "max(seqno) as SeqNo", "1=1");
                    strSeqNo =CvtFunc .ToString ( CvtFunc.ToInt(strSeqNo) + 1);
                    string strSQL = " Insert into mOutputHistory(SeqNo, OutputDate,UserName,Remark,HospitalID,HospitalName   )" +
                                    " Values ('" + strSeqNo + "', '" + BaseFunctions.FormatDate(DateTime.Now.Date.ToString(), DateFormatOption.DateFmtYMD) + "', " +
                                    " '"+ SysVar.UserName +"' , '"+ txtRemark.Text  +"', '"+ SysVar.HospitalID  +"','"+ SysVar.HospitalName +"' "+                                    
                                    " ) ";
                    mdbcon.ExecuteSql(strSQL);
                    if (GenerateData(strPath, mdbcon))
                    {
                        FillData();
                        mdbcon.CommitTran();
                    }
                    else
                    {
                        mdbcon.RollbackTran();
                    }
                    mdbcon.CloseCon();
                    mdbcon = new DBAccess(false, false);
                }
            }
        }

        private void frmMoutputMtn_FormClosed(object sender, FormClosedEventArgs e)
        {
            SysVar.marrFormList.Remove(this.Name);
        }
        
    }
}
